/**
 * 音效管理工具
 * 负责加载、播放和控制网站中的所有音效
 */
class SoundManager {
  constructor() {
    this.sounds = {};
    this.isMuted = false;
    this.currentBgMusic = null;
    this.initialized = false;
    this.fallbackMode = false;
    this.loadingStatus = {
      total: 0,
      success: 0,
      failed: 0
    };
  }

  /**
   * 初始化并预加载所有音效
   */
  init() {
    if (this.initialized) return;

    // 基本音效
    this.register('click', '/sounds/click.mp3');
    this.register('success', '/sounds/success.mp3');
    this.register('whoosh', '/sounds/whoosh.mp3');
    this.register('epic', '/sounds/epic_background.mp3');
    this.register('level_up', '/sounds/level_up.mp3');
    this.register('achievement', '/sounds/achievement.mp3');
    this.register('notification', '/sounds/notification.mp3');
    this.register('hover', '/sounds/hover.mp3');
    
    this.initialized = true;
    
    // 记录初始化完成时间
    console.log(`音效系统初始化完成，时间: ${new Date().toLocaleTimeString()}`);
    
    // 添加网页可见性变化监听，以便在用户切换标签页时暂停音效
    document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
    
    // 添加用户交互事件监听器，以解锁音频
    this.unlockAudioOnNextUserInteraction();
  }
  
  register(name, path) {
    this.sounds[name] = {
      path,
      audio: null,
      loaded: false
    };
  }

  preload(name) {
    if (!this.sounds[name]) return;

    if (!this.sounds[name].audio) {
      const audio = new Audio(this.sounds[name].path);
      audio.preload = 'auto';
      this.sounds[name].audio = audio;
      
      // 标记为已加载
      audio.addEventListener('canplaythrough', () => {
        this.sounds[name].loaded = true;
      });
    }
  }
  
  /**
   * 处理页面可见性变化
   */
  handleVisibilityChange() {
    if (document.hidden) {
      // 当页面不可见时，暂停所有音效
      this.pauseAll();
    }
  }
  
  /**
   * 播放指定音效
   * @param {string} name - 音效名称
   */
  play(name, options = {}) {
    if (!this.sounds[name] || this.isMuted || this.fallbackMode) return;

    // 如果音频还没创建，先创建它
    if (!this.sounds[name].audio) {
      this.preload(name);
    }

    const audio = this.sounds[name].audio;
    
    // 设置音量
    if (options.volume !== undefined) {
      audio.volume = options.volume;
    } else {
      audio.volume = 0.5; // 默认音量
    }
    
    // 设置循环
    audio.loop = options.loop || false;
    
    // 如果这是背景音乐，先停止当前播放的背景音乐
    if (options.isBackground && this.currentBgMusic && this.currentBgMusic !== name) {
      this.stop(this.currentBgMusic);
      this.currentBgMusic = name;
    }
    
    // 尝试播放
    try {
      const playPromise = audio.play();
      
      // 处理自动播放限制
      if (playPromise !== undefined) {
        playPromise.catch(error => {
          // 自动播放被阻止
          console.log('Auto-play was prevented:', error);
          
          // 绑定到用户交互事件
          const playOnInteraction = () => {
            audio.play().then(() => {
              document.removeEventListener('click', playOnInteraction);
              document.removeEventListener('touchstart', playOnInteraction);
            }).catch(err => console.error('Failed to play on interaction:', err));
          };
          
          document.addEventListener('click', playOnInteraction);
          document.addEventListener('touchstart', playOnInteraction);
        });
      }
    } catch (err) {
      console.error('Error playing sound:', err);
    }
  }
  
  /**
   * 停止指定音效
   * @param {string} name - 音效名称
   */
  stop(name) {
    if (!this.sounds[name] || !this.sounds[name].audio) return;

    const audio = this.sounds[name].audio;
    audio.pause();
    audio.currentTime = 0;
    
    // 如果这是当前背景音乐，清除它
    if (this.currentBgMusic === name) {
      this.currentBgMusic = null;
    }
  }
  
  /**
   * 暂停所有音效
   */
  pauseAll() {
    if (!this.initialized) return;
    
    Object.values(this.sounds).forEach(sound => {
      try {
        sound.audio.pause();
      } catch (e) {
        // 忽略暂停错误
      }
    });
  }
  
  /**
   * 设置所有音效的静音状态
   * @param {boolean} muted - 是否静音
   */
  setMuted(muted) {
    this.isMuted = muted;
    
    if (muted) {
      this.pauseAll();
    }
    
    return this.isMuted;
  }
  
  /**
   * 切换静音状态
   * @returns {boolean} 新的静音状态
   */
  toggleMute() {
    return this.setMuted(!this.isMuted);
  }
  
  /**
   * 获取静音状态
   * @returns {boolean} 是否静音
   */
  isMuted() {
    return this.isMuted;
  }
  
  /**
   * 显示音效缺失提示
   */
  showAudioMissingAlert() {
    if (this.alertShown) return;
    this.alertShown = true;
    
    console.warn('音效文件缺失或加载失败，请按照以下步骤生成音效文件：');
    console.warn('1. 打开 /public/sounds/generate-simple.html');
    console.warn('2. 点击页面中的按钮生成音效');
    console.warn('3. 将生成的音效文件保存到 /public/sounds/ 目录');
    
    // 仅在开发环境显示提示
    if (process.env.NODE_ENV === 'development') {
      const alertEl = document.createElement('div');
      alertEl.style.position = 'fixed';
      alertEl.style.bottom = '20px';
      alertEl.style.right = '20px';
      alertEl.style.padding = '15px';
      alertEl.style.background = 'rgba(255, 200, 200, 0.9)';
      alertEl.style.border = '1px solid #f88';
      alertEl.style.borderRadius = '5px';
      alertEl.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
      alertEl.style.zIndex = '9999';
      alertEl.style.maxWidth = '400px';
      alertEl.style.fontSize = '14px';
      
      alertEl.innerHTML = `
        <div style="font-weight:bold;margin-bottom:10px;color:#c22;">音效文件加载失败</div>
        <p style="margin:0 0 10px 0;line-height:1.5;">请确保音效文件已正确生成并放置在正确位置：</p>
        <ol style="margin:0;padding-left:20px;line-height:1.5;">
          <li>打开 /public/sounds/generate-simple.html</li>
          <li>点击页面中的按钮生成音效</li>
          <li>将生成的音效文件保存到 /public/sounds/ 目录</li>
        </ol>
        <button onclick="this.parentNode.remove()" style="margin-top:10px;padding:5px 10px;background:#f44;color:white;border:none;border-radius:3px;cursor:pointer;">关闭</button>
      `;
      
      document.body.appendChild(alertEl);
      
      // 5秒后自动关闭
      setTimeout(() => {
        if (alertEl.parentNode) {
          alertEl.remove();
        }
      }, 10000);
    }
  }

  /**
   * 检测音效文件是否存在
   */
  async checkSoundAvailability() {
    const soundsToCheck = [
      '/sounds/drumroll.mp3',
      '/sounds/reveal.mp3',
      '/sounds/applause.mp3'
    ];
    
    for (const soundPath of soundsToCheck) {
      try {
        const response = await fetch(soundPath, { method: 'HEAD' });
        if (!response.ok) {
          console.warn(`音效文件 ${soundPath} 不存在或无法访问`);
        } else {
          console.log(`音效文件 ${soundPath} 检测正常`);
        }
      } catch (e) {
        console.warn(`检测音效文件 ${soundPath} 时出错:`, e);
      }
    }
  }

  /**
   * 释放资源
   */
  dispose() {
    Object.values(this.sounds).forEach(sound => {
      sound.audio.pause();
      sound.audio.src = '';
    });
    this.sounds = {};
    this.initialized = false;
  }

  /**
   * 在下一次用户交互时解锁音频
   */
  unlockAudioOnNextUserInteraction() {
    const unlockAudio = () => {
      // 尝试播放一个静音音频来解锁
      const silentSound = new Audio('/sounds/silence.mp3');
      silentSound.play().then(() => {
        console.log('音频已解锁');
      }).catch(e => {
        console.warn('解锁音频失败', e);
      });
      
      // 移除事件监听器
      document.removeEventListener('click', unlockAudio);
      document.removeEventListener('touchstart', unlockAudio);
    };
    
    // 添加事件监听器
    document.addEventListener('click', unlockAudio);
    document.addEventListener('touchstart', unlockAudio);
  }
}

// 创建单例实例
const soundManager = new SoundManager();

// 导出单例
export default soundManager; 